# -*- coding:utf-8 -*-
__author__ = 'gin.chen'
from constant_util import Properties, __redis_config_file, logger

import redis


def connect_redis():
    redis_info = Properties(__redis_config_file).get_properties()
    pool = redis.ConnectionPool(**redis_info)
    try:
        return redis.Redis(connection_pool=pool)
    except Exception as err:
        # TODO 怎么将err打印到log
        # logger.error("redis 连接出错%s",)
        raise err


class RedisOperator:
    def __init__(self, key='exec_id'):
        self.redis_connect = connect_redis()
        self.key = key

    def add2redis(self, value):
        result = self.redis_connect.sadd(self.key, value)
        logger.debug("添加exec_id %d到redis的key %s中成功！", value, self.key)
        return result

    def remove2redis(self, value):
        result = self.redis_connect.srem(self.key, value)
        logger.debug("删除exec_id %d在redis的key %s中成功！", value, self.key)
        return result

    def get_all2redis(self):
        r = self.redis_connect.smembers(self.key)
        result = []
        for i in r:
            result.append(i.decode(encoding='utf-8'))

        logger.debug("获取key%s中的所有值成功！", self.key)
        return result

    def is_key_not_exist(self):
        if self.redis_connect.exists(self.key):
            return 0
        else:
            return 1


if __name__ == '__main__':
    ro = RedisOperator()
    # value = 5555
    # print(ro.add2redis(value=4534))
    if ro.is_key_not_exist():
        ro.add2redis("")
    print(ro.get_all2redis())
